<template>
  <view class="product-card product-description">
    <view v-if="variables.length">
      <view class="card-title">{{ $t('product.product_variable') }}</view>
      <view class="variable-wrap">
        <view class="variable-group mb-2" v-for="(variable, variable_index) in variables" :key="variable_index">
          <view class="title">{{ variable.name }}</view>
          <view class="variable-info">
            <view
              v-for="(value, value_index) in variable.values"
              @click="checkedVariableValue(variable_index, value_index, value)"
              :key="value_index"
              :class="[value.selected ? 'selected' : '', value.disabled ? 'disabled' : '']"
            >
              <view class="image" v-if="value.image"><image :src="value.image" mode="widthFix" class="img" /></view>
              {{ value.name }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="quantity-wrap">
      <view class="title">{{ $t('product.product_buy_quantity') }}</view>
      <view><uni-number-box v-model="quantity" @change="quantityChange" :max="maxQuantity" :min="1" /></view>
    </view>
  </view>
</template>

<script setup>
import { toRefs, ref, computed, defineEmits } from "vue"
const { proxy } = getCurrentInstance()
import { t } from '@/locale/index'
const props = defineProps({
  variables: {
    type: Array,
    default: () => [],
  },
  skus: {
    type: Array,
    default: () => [],
  },
})

const { variables, skus } = toRefs(props)

const quantity = ref(1)
const maxQuantity = ref(0)

const emits = defineEmits(["change, quantityChange"])

let selectedVariantsIndex = [] // 选中的变量索引

const formatVariables = () => {
  selectedVariantsIndex = JSON.parse(JSON.stringify(skus.value.find((e) => e.is_default).variants))
  variables.value = variables.value.map((variable) => {
    variable.values.forEach((value) => {
      value.selected = false
      value.disabled = false
    })
    return variable
  })

  checkedVariants()
  updateSelectedSku(false)
  updateSelectedVariantsStatus()
}

const updateSelectedSku = (reload = true) => {
  let sku = skus.value.find((s) => s.variants.toString() == selectedVariantsIndex.toString())
  maxQuantity.value = sku ? sku.quantity : ''

  if (quantity.value > maxQuantity.value) {
    quantity.value = maxQuantity.value
  }

  if (!quantity.value && maxQuantity.value) {
    quantity.value = 1
  }

  emits("change", sku, reload)
}

const quantityChange = (e) => {
  if (e == maxQuantity.value) {
    proxy.$util.msg(t('product.max_quantity') + maxQuantity.value)
    quantity.value = maxQuantity.value
  } else {
    quantity.value = e
  }

  emits("quantityChange", e)
}

const updateSelectedVariantsStatus = () => {
  // skus 里面 quantity 不为 0 的 sku.variants
  const skuss = skus.value.filter((sku) => sku.quantity > 0).map((sku) => sku.variants)
  variables.value.forEach((variable, index) => {
    variable.values.forEach((value, value_index) => {
      const selectedVariantsIndexs = selectedVariantsIndex.slice(0)

      selectedVariantsIndexs[index] = value_index
      const selectedSku = skuss.find((sku) => sku.toString() == selectedVariantsIndexs.toString())
      if (selectedSku) {
        value.disabled = false
      } else {
        value.disabled = true
      }
    })
  })
}

const checkedVariableValue = (variable_index, value_index, value) => {
  variables.value[variable_index].values.forEach((v, i) => {
    v.selected = i == value_index
  })

  updateSelectedVariantsIndex()
  updateSelectedSku()
  updateSelectedVariantsStatus()
}

const updateSelectedVariantsIndex = () => {
  // 获取选中的 variables 内 value的 下标 index 填充到 selectedVariantsIndex 中
  variables.value.forEach((variable, index) => {
    variable.values.forEach((value, value_index) => {
      if (value.selected) {
        selectedVariantsIndex[index] = value_index
      }
    })
  })
}

// 把对应 selectedVariantsIndex 下标选中 variables -> values 的 selected 字段为 true
const checkedVariants = () => {
  variables.value.forEach((variable, index) => {
    variable.values[selectedVariantsIndex[index]].selected = true
  })
}

defineExpose({ formatVariables })
</script>

<style lang="scss" scoped>
@import "../card-title.scss";

.quantity-wrap {
  .title {
    margin-bottom: 10rpx;
    font-size: 28rpx;
  }
}

.variable-wrap {
  margin-top: 10rpx;

  .title {
    margin-bottom: 10rpx;
    font-size: 28rpx;
  }

  .variable-info {
    > view {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
      border: 1px solid #eee;
      margin-left: 0;
      min-width: 50rpx;
      border-radius: 20px;
      padding: 10rpx 30rpx;
      font-weight: bold;
      text-align: center;
      font-size: 24rpx;
      flex-direction: column;

      &:hover,
      &.selected {
        border-color: #222;
      }

      > .image {
        width: 50px;
        margin-top: -0.5rpx;
        margin-left: -0.5rpx;
        margin-right: -0.5rpx;
        margin-bottom: 6px;
      }

      &:not(.selected) {
        &.disabled {
          border: 1px dashed #bfbfbf;
          color: #999;
          font-weight: initial;
        }
      }
    }
  }
}
</style>
